package com.ptp.backendcertms.token.service.impl;

import com.ptp.backendcertms.basiccompnents.properties.ProjectProperties;
import com.ptp.backendcertms.token.service.ITokenService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements ITokenService {

    @Resource
    private ProjectProperties projectProperties;


    @Override
    public String createToken(String uid, Long time) {
        return createTokenWithUserKey(uid, time, "login_user_key");

    }


    /**
     * 生成token
     */
    private String createTokenWithUserKey(String uid, Long time, String userKey) {
        // 可拓展其他参数
        Map<String, Object> claims = new HashMap<>();
        claims.put(userKey, uid);
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, projectProperties.getLoginSecret().getSecret());
        // 使用claims时非显示声明Expiration会导致Expiration失效
        jwtBuilder.setExpiration(new Date(System.currentTimeMillis() + time));
        return jwtBuilder.compact();
    }


}
